package com.dat255.tentatime;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dat255.tentatime.es.ExternalStorage;
/**
 * This activity is our main activity
 * The task for this activity is to assist  the user to retrieve
 * general information about an exam for a course at Chalmers University
 * @author Joseph
 * @version 2.3
 */

// TODO: Onclick method, the section inside needs to be moved to a asynctask
// TODO: Some more comments
// TODO: Some Toast msg needs to be moved to string res
public class FindActivity extends Activity implements OnClickListener {
	
	//The input field for the textbox
	private EditText editSearch;
	// The search button
	private Button buttonFind;
	//Error msg
	private String err_msg;
	private static final int DIALOG_ID = 47;


	
	
    /** 
     * Called when the activity is first created. 
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	
    	super.onCreate(savedInstanceState);
    	//Sets the layout of the activity
        setContentView(R.layout.find);
        //Attach input/output controls 
        this.AttachGUIcomponents();
        //Initiate listener for the button
        buttonFind.setOnClickListener(this);
        
  
    }
  

    /**
     * This method is invoked when the user presses the button
     * The method will validate the input-data and assist the user 
     * if wrong information was entered
     */
	@Override
	public void onClick(View v) {
		//Save the user entered data
		String userdata = editSearch.getText().toString();
		
		//Check if ther is an valid internet connection
		if(this.connectedToTheInternet()){
		
				// 1. Validate user entered data
				// 2. Check if the entered data was a course id or a course name
				if(InputUtility.validateCourseID(userdata)){
					
					showDialog(DIALOG_ID);
				    new SearchForexam().execute(userdata);
						
				}else if(InputUtility.validateName(userdata)){
						
					try {

						moveToNextActivity((ArrayList<Exam>) ExternalStorage.findByName(userdata));
					} catch (java.net.SocketTimeoutException e){
						Toast.makeText(this,"The server is busy, Try later!",Toast.LENGTH_LONG).show();
					}catch (Exception e) {
			
						Toast.makeText(this,"Problems",Toast.LENGTH_LONG).show();
					}
						
						
				}else{
					
				// 3. The user data was incorrect, a message will inform the user	
					Toast.makeText(this,R.string.toastWrongInput,Toast.LENGTH_LONG).show();
					
				}
		}else{
			// 4. The phone is not connected to the internet, no network connection
			Toast.makeText(this,R.string.toastnoInterner,Toast.LENGTH_LONG).show();
			
		}
	
	}

	
	/*****************************************************/
	/******************** MENU ***************************/
	/*****************************************************/
	
	
	/**
	 * Creates the menu, with the menu-items specified in the menu xml file
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}


	/**
	 * Action for a selected menu item
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()){
		
		//Favourite button
		case R.id.itemFav:
			startActivity(new Intent(this,FavouriteActivity.class));
			break;
		//Find button
		case R.id.itemFind:
			startActivity(new Intent(this, FindActivity.class));
			break;
		
		}
	
		return true;
	}
	
	/*****************************************************/
	/************** PRIVATE METHODS **********************/
	/*****************************************************/
	
	 /**
     * The internal method will "connect" the input/output components
     * of the GUI for this activity for use in this code
     */
    private void AttachGUIcomponents(){
    	
        editSearch = (EditText) findViewById(R.id.editSearch);
        buttonFind = (Button) findViewById(R.id.buttonFind);
    	
    }
	/**
	 *  After retrieving results from the server move to next activity
	 * @param list the found exams
	 */
		private void moveToNextActivity(ArrayList<Exam> resultlist){
			
			//Create new intent, move to the result list for reviewing the searched exams
			Intent intent = new Intent(FindActivity.this, ResultActivity.class);
			//Place the found exams to the next activity
			intent.putParcelableArrayListExtra(
					FindActivity.this.getString(R.string.keyResultList), resultlist );
			//Start the new activity
			FindActivity.this.startActivity(intent); 
			
			
		}
		
		/**
		 * This method will check if the phone is connected to the Internet
		 * @return
		 */
		private boolean connectedToTheInternet() {
		    ConnectivityManager conMan = (ConnectivityManager) 
		    		getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo netInfo = conMan.getActiveNetworkInfo();
		   
		    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
		        return true;
		    }
		    return false;
		}
		
		 // //////// Dialog Stuff
		  @Override
		  protected Dialog onCreateDialog(int id) {
		    switch (id) {
		    case DIALOG_ID: {
		      ProgressDialog dialog = new ProgressDialog(this);
		      dialog.setMessage("Please wait");
		      dialog.setIndeterminate(true);
		      dialog.setCancelable(true);
		      return dialog;
		    }
		    }

		    return null;
		  }
	private class SearchForexam extends AsyncTask<String,Integer,Exam>{

		@Override
		protected Exam doInBackground(String... userdata) {
			Exam exam = null;
			
			try {
				
				exam = ExternalStorage.findById(userdata[0]);
				
			} catch (java.net.SocketTimeoutException e){
				  
				err_msg = "The server is busy, Try later!";
			}catch (Exception e) {
				err_msg = "Database down!";
			}
			
			return exam;
		}

		@Override
		protected void onPostExecute(Exam result) {
			
			
			super.onPostExecute(result);
			dismissDialog(DIALOG_ID);
			
			if(result == null){
				
				Toast.makeText(FindActivity.this,err_msg,Toast.LENGTH_LONG).show();
				
			}else{
				
				ArrayList<Exam> searchList = new ArrayList<Exam>();
				searchList.add(result);
				FindActivity.this.moveToNextActivity(searchList);
				
			}
			
			
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
		
		
		
		
	}

}